package com.yuehuanghun.admin.generator.util;

import java.text.Collator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.yuehuanghun.admin.generator.config.GenConstants;
import com.yuehuanghun.admin.generator.domain.GenTable;
import com.yuehuanghun.admin.generator.domain.GenTableColumn;
import com.yuehuanghun.framework.json.JSON;
import com.yuehuanghun.framework.json.JSONObject;
import com.yuehuanghun.framework.util.DateUtils;
import com.yuehuanghun.framework.util.StringUtils;

/**
 * 模板处理工具类
 * 
 * @author yadmin
 */
public class EnjoyUtils {
	/** 项目空间路径 */
	private static final String PROJECT_PATH = "main/java";

	/** mybatis空间路径 */
	private static final String MYBATIS_PATH = "main/resources/mapper";

	/** 默认上级菜单，系统工具 */
	private static final String DEFAULT_PARENT_MENU_ID = "3";

	/**
	 * 设置模板变量信息
	 *
	 * @return 模板列表
	 */
	public static Map<String, Object> prepareTemplateParams(GenTable genTable) {
		String moduleName = genTable.getModuleName();
		String businessName = genTable.getBusinessName();
		String packageName = genTable.getPackageName();
		String tplCategory = genTable.getTplCategory();
		String functionName = genTable.getFunctionName();

		Map<String, Object> templateParams = new HashMap<>();
		templateParams.put("tplCategory", genTable.getTplCategory());
		templateParams.put("tableName", genTable.getTableName());
		templateParams.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : "【请填写功能名称】");
		templateParams.put("ClassName", genTable.getClassName());
		templateParams.put("className", StringUtils.uncapitalize(genTable.getClassName()));
		templateParams.put("moduleName", genTable.getModuleName());
		templateParams.put("BusinessName", StringUtils.capitalize(genTable.getBusinessName()));
		templateParams.put("businessName", genTable.getBusinessName());
		templateParams.put("basePackage", getPackagePrefix(packageName));
		templateParams.put("packageName", packageName);
		templateParams.put("author", genTable.getFunctionAuthor());
		templateParams.put("datetime", DateUtils.getDate());
		templateParams.put("pkColumn", genTable.getPkColumn());
		templateParams.put("importList", getImportList(genTable));
		templateParams.put("permissionPrefix", getPermissionPrefix(moduleName, businessName));
		templateParams.put("columns", genTable.getColumns());
		templateParams.put("table", genTable);
		setMenuParams(templateParams, genTable);
		if (GenConstants.TPL_TREE.equals(tplCategory)) {
			setTreeTableParams(templateParams, genTable);
		}
		if (GenConstants.TPL_SUB.equals(tplCategory)) {
			setSubTableParams(templateParams, genTable);
		}
		return templateParams;
	}

	public static void setMenuParams(Map<String, Object> templateParams, GenTable genTable) {
		String options = genTable.getOptions();
		JSONObject paramsObj = JSON.parseObject(options);
		String parentMenuId = getParentMenuId(paramsObj);
		templateParams.put("parentMenuId", parentMenuId);
	}

	public static void setTreeTableParams(Map<String, Object> templateParams, GenTable genTable) {
		String options = genTable.getOptions();
		JSONObject paramsObj = JSON.parseObject(options);
		String treeCode = getTreecode(paramsObj);
		String treeParentCode = getTreeParentCode(paramsObj);
		String treeName = getTreeName(paramsObj);

		templateParams.put("treeCode", treeCode);
		templateParams.put("treeParentCode", treeParentCode);
		templateParams.put("treeName", treeName);
		templateParams.put("expandColumn", getExpandColumn(genTable));
		if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) {
			templateParams.put("tree_parent_code", paramsObj.getString(GenConstants.TREE_PARENT_CODE));
		}
		if (paramsObj.containsKey(GenConstants.TREE_NAME)) {
			templateParams.put("tree_name", paramsObj.getString(GenConstants.TREE_NAME));
		}
	}

	public static void setSubTableParams(Map<String, Object> templateParams, GenTable genTable) {
		GenTable subTable = genTable.getSubTable();
		String subTableName = genTable.getSubTableName();
		String subTableFkName = genTable.getSubTableFkName();
		String subClassName = genTable.getSubTable().getClassName();
		String subTableFkClassName = StringUtils.convertToCamelCase(subTableFkName);

		templateParams.put("subTable", subTable);
		templateParams.put("subTableName", subTableName);
		templateParams.put("subTableFkName", subTableFkName);
		templateParams.put("subTableFkClassName", subTableFkClassName);
		templateParams.put("subTableFkclassName", StringUtils.uncapitalize(subTableFkClassName));
		templateParams.put("subClassName", subClassName);
		templateParams.put("subclassName", StringUtils.uncapitalize(subClassName));
		templateParams.put("subImportList", getImportList(genTable.getSubTable()));
	}

	/**
	 * 获取模板信息
	 *
	 * @return 模板列表
	 */
	public static List<String> getTemplateList(String tplCategory) {
		List<String> templates = new ArrayList<String>();
		templates.add("ej/java/domain.java.ej");
		templates.add("ej/java/mapper.java.ej");
		templates.add("ej/java/service.java.ej");
		templates.add("ej/java/serviceImpl.java.ej");
		templates.add("ej/java/controller.java.ej");
		templates.add("ej/xml/mapper.xml.ej");
		templates.add("ej/sql/sql.ej");
		templates.add("ej/js/api.js.ej");
		if (GenConstants.TPL_CRUD.equals(tplCategory)) {
			templates.add("ej/vue/index.vue.ej");
		} else if (GenConstants.TPL_TREE.equals(tplCategory)) {
			templates.add("ej/vue/index-tree.vue.ej");
		} else if (GenConstants.TPL_SUB.equals(tplCategory)) {
			templates.add("ej/vue/index.vue.ej");
//			templates.add("ej/java/sub-domain.java.ej");
		}
		return templates;
	}

	/**
	 * 获取文件名
	 */
	public static String getFileName(String template, GenTable genTable) {
		// 文件名称
		String fileName = "";
		// 包路径
		String packageName = genTable.getPackageName();
		// 模块名
		String moduleName = genTable.getModuleName();
		// 大写类名
		String className = genTable.getClassName();
		// 业务名称
		String businessName = genTable.getBusinessName();

		String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/");
		String mybatisPath = MYBATIS_PATH + "/" + moduleName;
		String vuePath = "vue";

		if (template.contains("domain.java.ej")) {
			fileName = StringUtils.format("{}/domain/{}.java", javaPath, className);
		}
		if (template.contains("sub-domain.java.ej")
				&& StringUtils.equals(GenConstants.TPL_SUB, genTable.getTplCategory())) {
			fileName = StringUtils.format("{}/domain/{}.java", javaPath, genTable.getSubTable().getClassName());
		} else if (template.contains("mapper.java.ej")) {
			fileName = StringUtils.format("{}/mapper/{}Mapper.java", javaPath, className);
		} else if (template.contains("service.java.ej")) {
			fileName = StringUtils.format("{}/service/I{}Service.java", javaPath, className);
		} else if (template.contains("serviceImpl.java.ej")) {
			fileName = StringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className);
		} else if (template.contains("controller.java.ej")) {
			fileName = StringUtils.format("{}/controller/{}Controller.java", javaPath, className);
		} else if (template.contains("mapper.xml.ej")) {
			fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className);
		} else if (template.contains("sql.ej")) {
			fileName = businessName + "Menu.sql";
		} else if (template.contains("api.js.ej")) {
			fileName = StringUtils.format("{}/api/{}/{}.js", vuePath, moduleName, businessName);
		} else if (template.contains("index.vue.ej")) {
			fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName);
		} else if (template.contains("index-tree.vue.ej")) {
			fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName);
		}
		return fileName;
	}

	/**
	 * 获取包前缀
	 *
	 * @param packageName 包名称
	 * @return 包前缀名称
	 */
	public static String getPackagePrefix(String packageName) {
		int lastIndex = packageName.lastIndexOf(".");
		String basePackage = StringUtils.substring(packageName, 0, lastIndex);
		return basePackage;
	}

	/**
	 * 根据列类型获取导入包
	 * 
	 * @param genTable 业务表对象
	 * @return 返回需要导入的包列表
	 */
	public static List<String> getImportList(GenTable genTable) {
		List<GenTableColumn> columns = genTable.getColumns();
		GenTable subGenTable = genTable.getSubTable();
		HashSet<String> importList = new HashSet<>();
		if (StringUtils.isNotNull(subGenTable)) {
			importList.add("java.util.List");
		}
		if(genTable.getTableName().matches("^[_A-Z]+$")) {
			importList.add("javax.persistence.Table");
		}
		for (GenTableColumn column : columns) {
			if (!column.isSuperColumn() && column.getJavaType().contains(GenConstants.TYPE_DATE)) {
				importList.add("com.fasterxml.jackson.annotation.JsonFormat");
			}
			if(column.getJavaType().contains(".")) {
				importList.add(column.getJavaType());
				column.setJavaType(column.getJavaType().substring(column.getJavaType().lastIndexOf(".") + 1));
			}
			importList.add("javax.validation.constraints.NotNull");
			if("String".equals(column.getJavaType()) && column.isRequired()) {
				importList.add("javax.validation.constraints.NotBlank");
				importList.add("com.yuehuanghun.framework.domain.validate.group.Add");
			}
			if(column.getColumnLength() != null && column.getColumnLength() > 0) {
				importList.add("org.hibernate.validator.constraints.Length");
			}
			if(column.isPk() && !column.isIncrement()) {
				if(column.isIncrement()) {
					importList.add("javax.persistence.Id");
				} else if(StringUtils.equalsAny(column.getJavaType(), "Long", "String")){				
					importList.add("javax.persistence.GeneratedValue");
					importList.add("javax.persistence.GenerationType");
					importList.add("com.yuehuanghun.mybatis.milu.tool.Constants");
					if(StringUtils.equals(column.getJavaType(), "Long")) {
						importList.add("com.yuehuanghun.mybatis.milu.annotation.alias.id.SnowflakeId");
					} else if(StringUtils.equals(column.getJavaType(), "String")) {
						importList.add("com.yuehuanghun.mybatis.milu.annotation.alias.id.UUID");
					} else {
						importList.add("javax.persistence.Id");
					}
				}
			}
			if("createTime".equals(column.getJavaField())) {
				importList.add("com.yuehuanghun.admin.core.config.annotation.mybatislilu.CreateTime");
			} else if("updateTime".equals(column.getJavaField())) {
				importList.add("com.yuehuanghun.mybatis.milu.annotation.alias.attr.UpdateTime");
			} else if("createBy".equals(column.getJavaField())) {
				importList.add("com.yuehuanghun.admin.core.config.annotation.mybatislilu.CreateBy");
			} else if("updateBy".equals(column.getJavaField())) {
				importList.add("com.yuehuanghun.admin.core.config.annotation.mybatislilu.UpdateBy");
			} 
			if(column.getColumnName().matches("^[_A-Z]+$")) { //ORCLE全大写时
				importList.add("javax.persistence.Column");
			}
			if(column.getJavaField().contains("Time") || column.getJavaField().contains("Date")) {
				importList.add("com.fasterxml.jackson.annotation.JsonFormat");
			}
			if(StringUtils.equals("Long", column.getJavaType())) {
				importList.add("com.fasterxml.jackson.annotation.JsonFormat.Shape");
			}

			if("BETWEEN".equals(column.getQueryType())) {
				importList.add("com.yuehuanghun.mybatis.milu.annotation.AttributeOptions");
				importList.add("com.yuehuanghun.mybatis.milu.annotation.ExampleQuery");
			}
			importList.add("com.yuehuanghun.framework.domain.validate.group.Update");
			importList.add("com.yuehuanghun.mybatis.milu.annotation.Filler");
			importList.add("javax.persistence.Column");
			importList.add("javax.persistence.Transient");
			importList.add("com.yuehuanghun.framework.annotation.Excel");
		}

		Collator collator =  Collator.getInstance();
		return importList.stream().sorted((o1, o2) -> collator.compare(o1, o2)).collect(Collectors.toList());
	}

	/**
	 * 获取权限前缀
	 *
	 * @param moduleName   模块名称
	 * @param businessName 业务名称
	 * @return 返回权限前缀
	 */
	public static String getPermissionPrefix(String moduleName, String businessName) {
		return StringUtils.format("{}:{}", moduleName, businessName);
	}

	/**
	 * 获取上级菜单ID字段
	 *
	 * @param paramsObj 生成其他选项
	 * @return 上级菜单ID字段
	 */
	public static String getParentMenuId(JSONObject paramsObj) {
		if (StringUtils.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.PARENT_MENU_ID)) {
			return paramsObj.getString(GenConstants.PARENT_MENU_ID);
		}
		return DEFAULT_PARENT_MENU_ID;
	}

	/**
	 * 获取树编码
	 *
	 * @param paramsObj 生成其他选项
	 * @return 树编码
	 */
	public static String getTreecode(JSONObject paramsObj) {
		if (paramsObj.containsKey(GenConstants.TREE_CODE)) {
			return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_CODE));
		}
		return StringUtils.EMPTY;
	}

	/**
	 * 获取树父编码
	 *
	 * @param paramsObj 生成其他选项
	 * @return 树父编码
	 */
	public static String getTreeParentCode(JSONObject paramsObj) {
		if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) {
			return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_PARENT_CODE));
		}
		return StringUtils.EMPTY;
	}

	/**
	 * 获取树名称
	 *
	 * @param paramsObj 生成其他选项
	 * @return 树名称
	 */
	public static String getTreeName(JSONObject paramsObj) {
		if (paramsObj.containsKey(GenConstants.TREE_NAME)) {
			return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_NAME));
		}
		return StringUtils.EMPTY;
	}

	/**
	 * 获取需要在哪一列上面显示展开按钮
	 *
	 * @param genTable 业务表对象
	 * @return 展开按钮列序号
	 */
	public static int getExpandColumn(GenTable genTable) {
		String options = genTable.getOptions();
		JSONObject paramsObj = JSON.parseObject(options);
		String treeName = paramsObj.getString(GenConstants.TREE_NAME);
		int num = 0;
		for (GenTableColumn column : genTable.getColumns()) {
			if (column.isList()) {
				num++;
				String columnName = column.getColumnName();
				if (columnName.equals(treeName)) {
					break;
				}
			}
		}
		return num;
	}
}
